package cn.vc.shop.config;

import cn.vc.shop.entity.po.Shop;
import cn.vc.shop.entity.po.ShopAct;
import cn.vc.shop.mapper.ShopActMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class CaffeineConfig {
    @Autowired
    private ShopActMapper shopActMapper;

    @Bean
    public Cache<String, Shop> shopCache() {
        return Caffeine.newBuilder()
                .initialCapacity(1000)
                .maximumSize(10)//最多缓存10条
                .build();
    }
    @Bean
    public Cache<String, ShopAct> shopActCache() {
        return Caffeine.newBuilder()
                .initialCapacity(1000)
                .maximumSize(10)//最多缓存10条
                .refreshAfterWrite(10, TimeUnit.MINUTES)//在最后一次写入后10分钟过期
                .build(new CacheLoader<String, ShopAct>() {
                    // 第一次刷新机制
                    @Override
                    public @Nullable ShopAct load(@NonNull String s) throws Exception {
                        return shopActMapper.selectById(s.split(":")[1]);
                    }
                    // 第二次之后刷新机制
                    @Override
                    public @Nullable ShopAct reload(@NonNull String key, @NonNull ShopAct oldValue) throws Exception {
                        return shopActMapper.selectById(oldValue.getId());
                    }
                });
    }
}
